﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using myBoard.App.Components.MagnetsStore.ViewsModels;

namespace myBoard.App
{
    public partial class CategorySelector : UserControl
	{
        public CategoriesViewModel ItemsSource
        {
            get { return (CategoriesViewModel)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        public CategoriesViewModel CheckedItems
        {
            get { return (CategoriesViewModel)GetValue(CheckedItemsProperty); }
            set { SetValue(CheckedItemsProperty, value); }
        }
        
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource", typeof(CategoriesViewModel), typeof(CategorySelector), new UIPropertyMetadata(ItemsSourceChanged));

        public static readonly DependencyProperty CheckedItemsProperty =
            DependencyProperty.Register("CheckedItems", typeof(CategoriesViewModel), typeof(CategorySelector), new UIPropertyMetadata(CheckedItemsChanged));


        private static void ItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            
        }       

        private static void CheckedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CategorySelector categorySelector = d as CategorySelector;
            CategoriesViewModel allCategories = categorySelector._categoriesLbx.DataContext as CategoriesViewModel;
            CategoriesViewModel checkedCategories = e.NewValue as CategoriesViewModel;
            foreach (CategoryViewModel cvm in allCategories)
            {
                cvm.IsChecked = false;

                for(int i=0;i<checkedCategories.Count;i++)
                {
                    CategoryViewModel checkedCategory = checkedCategories[i];
                    if (cvm.Id == checkedCategory.Id)
                    {
                        cvm.IsChecked = true;
                    }
                }
            }
        }

		public CategorySelector()
		{
			this.InitializeComponent();
		}

		private void _catChk_Checked(object sender, System.Windows.RoutedEventArgs e)
		{
			CategoryViewModel cat = ((FrameworkElement)sender).DataContext as CategoryViewModel;
            CheckedItems.Add(cat);
		}

		private void _catChk_Unchecked(object sender, System.Windows.RoutedEventArgs e)
		{
            CategoryViewModel cat = ((FrameworkElement)sender).DataContext as CategoryViewModel;
            CheckedItems.Remove(cat);
		}
	}
}